package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.reggie.common.BaseContext;
import com.reggie.common.CustomException;
import com.reggie.common.R;
import com.reggie.dto.MyOrders;
import com.reggie.entity.*;
import com.reggie.mapper.OrdersMapper;
import com.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    /*
    * 用户下单
    * 提价的下单数据：Orders(id=null, number=null, status=null, userId=null,
    *  addressBookId=1569216108848750594, orderTime=null, checkoutTime=null,
    * payMethod=1, amount=null, remark=, userName=null, phone=null, address=null, consignee=null)
    * */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //当前用户id
        Long userId = BaseContext.getCurrentId();
        //当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if (shoppingCarts==null||shoppingCarts.size()==0){
            throw new CustomException("购物车为空，无法下单");
        }
        //用户数据
        User user = userService.getById(userId);
        //地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null){
            throw new CustomException("地址信息有误，无法下单");
        }
        //向订单表插入数据
        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount=new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.get()));//支付金额
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName()==null?"":addressBook.getProvinceName())
                +(addressBook.getCityName()==null?"":addressBook.getCityName())
                +(addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                +(addressBook.getDetail()==null?"":addressBook.getDetail()));

        //向订单表中插入数据
        this.save(orders);
        //向订单明细表中插入数据，多条
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }

    /*
    * 历史订单（有订单和订单明细）
    * */
    @Override
    public Page<MyOrders> historyList(int page, int pageSize) {
        /*//获取当前用户的id
        Long userId = BaseContext.getCurrentId();
        //根据userId查询orders列表
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper=new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        List<Orders> list = this.list(ordersLambdaQueryWrapper);
        //把orders中的内容复制到myOrders中,
        List<MyOrders> myOrdersList = list.stream().map(new Function<Orders, MyOrders>() {
            @Override
            public MyOrders apply(Orders orders) {
                //此时orders中的orderDetails还是空的
                MyOrders myOrders = new MyOrders();
                BeanUtils.copyProperties(orders, myOrders);
                //根据order表中的number（订单号）,查询order——drtail表中的数据
                String number = orders.getNumber();
                LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, number);
                List<OrderDetail> list1 = orderDetailService.list(orderDetailLambdaQueryWrapper);
                myOrders.setOrderDetails(list1);
                return myOrders;
            }
        }).collect(Collectors.toList());
        for (MyOrders myOrders : myOrdersList) {
            System.out.println("测试历史订单数据："+myOrders.toString());
        }
        return myOrdersList;*/
        //获取当前用户的id
        Long userId = BaseContext.getCurrentId();
        //订单分页构造器
        Page<Orders> pageInfo=new Page<>(page,pageSize);
        //我的订单分页构造器
        Page<MyOrders> myOrdersPage=new Page<>(page,pageSize);
        //查询orders中的所有信息
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(userId!=null,Orders::getUserId,userId);
        this.page(pageInfo,queryWrapper);
        //对象拷贝,不拷贝records，相当于myOrdersPage中包含所有的orders表中的信息
        BeanUtils.copyProperties(pageInfo,myOrdersPage,"records");
        //查询订单明细，根据订单id
        List<Orders> records = pageInfo.getRecords();
        List<MyOrders> list = records.stream().map(new Function<Orders, MyOrders>() {
            @Override
            public MyOrders apply(Orders orders) {
                System.out.println("orders:"+orders.toString());
                MyOrders myOrders = new MyOrders();
                BeanUtils.copyProperties(orders, myOrders);

                System.out.println("myOrders:"+myOrders.toString());
                System.out.println(orders.getId());
                //查询详细订单列表
                String number = orders.getNumber();
                LambdaQueryWrapper<OrderDetail> queryWrapper1=new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderDetail::getOrderId,number);
                List<OrderDetail> list1 = orderDetailService.list(queryWrapper1);
                myOrders.setOrderDetails(list1);
                log.info("历史订单：{}",myOrders.toString());
                return myOrders;
            }
        }).collect(Collectors.toList());
        myOrdersPage.setRecords(list);
        return myOrdersPage;
    }

    /*
    * 后台的订单查询分页
    * */
    @Override
    public Page<MyOrders> pageOrder(int page, int pageSize) {
        /*Page<Orders> pageInfo=new Page<>(page,pageSize);
        this.page(pageInfo);
        //此时订单中的userName还是空的
        Page<MyOrders> myOrdersPage=new Page<>(page,pageSize);
        //赋值参数,records是当前页面数据
        BeanUtils.copyProperties(pageInfo,myOrdersPage,"records");
        //对当前页面进行处理，将userName数据插入到MyOrders对象中
        List<Orders> records = pageInfo.getRecords();
        records.stream().map(new Function<Orders, MyOrders>() {
            @Override
            public MyOrders apply(Orders orders) {
                MyOrders myOrders=new MyOrders();
                //将orders中的内容赋值到myOrders中去
                BeanUtils.copyProperties(orders,myOrders);
                //查询username------>orders表中有，想多了
            }
        })*/
        return null;
    }

    @Override
    public Page<MyOrders> userPage(int page, int pageSize) {
        //获取当前用户的id
        Long userId = BaseContext.getCurrentId();
        //订单分页构造器
        Page<Orders> pageInfo=new Page<>(page,pageSize);
        //我的订单分页构造器
        Page<MyOrders> myOrdersPage=new Page<>(page,pageSize);
        //查询orders中的所有信息
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(userId!=null,Orders::getUserId,userId).ne(Orders::getStatus,4);
        this.page(pageInfo,queryWrapper);
        //对象拷贝,不拷贝records，相当于myOrdersPage中包含所有的orders表中的信息
        BeanUtils.copyProperties(pageInfo,myOrdersPage,"records");
        //查询订单明细，根据订单id
        List<Orders> records = pageInfo.getRecords();
        List<MyOrders> list = records.stream().map(new Function<Orders, MyOrders>() {
            @Override
            public MyOrders apply(Orders orders) {
                System.out.println("orders:"+orders.toString());
                MyOrders myOrders = new MyOrders();
                BeanUtils.copyProperties(orders, myOrders);

                System.out.println("myOrders:"+myOrders.toString());
                System.out.println(orders.getId());
                //查询详细订单列表
                String number = orders.getNumber();
                LambdaQueryWrapper<OrderDetail> queryWrapper1=new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderDetail::getOrderId,number);
                List<OrderDetail> list1 = orderDetailService.list(queryWrapper1);
                myOrders.setOrderDetails(list1);
                log.info("我的订单：{}",myOrders.toString());
                return myOrders;
            }
        }).collect(Collectors.toList());
        myOrdersPage.setRecords(list);
        return myOrdersPage;
    }
}
